/**
 * 
 */
package weibo4j.examples;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import weibo4j.ShortUrl;
import weibo4j.Timeline;
import weibo4j.Users;
import weibo4j.examples.oauth2.Log;
import weibo4j.examples.util.QueueUtil;
import weibo4j.examples.util.Util;
import weibo4j.http.HttpClient;
import weibo4j.model.Comment;
import weibo4j.model.PostParameter;
import weibo4j.model.Status;
import weibo4j.model.StatusWapper;
import weibo4j.model.User;
import weibo4j.model.UserWapper;
import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONException;
import weibo4j.org.json.JSONObject;
import weibo4j.util.WeiboConfig;

/**
 * 微博测试
 * @author Administrator
 * 针对一个服务器IP的请求次数限制，测试授权： 1000次/小时 
      针对一个用户在使用一个应用的请求次数限制
		测试授权：

		总限制：单用户每应用 150次/小时
		发微博：单用户每应用 30次/小时
                发评论：单用户每应用 60次/小时
                加关注：单用户每应用 60次/小时 100次/天 

 */
public class WeiboTest {

	//获取粉丝列表
	public static List getUsersOfFensi(String access_token,String uid,int count){
		List list=new ArrayList();
		for(int i=0;i<=count;i=i+200){
			UserWapper users=WeiboRelation.getFollowersByUid(access_token,uid,200,i);
			for(int j=0;j<users.getUsers().size();j++){
				User u=users.getUsers().get(j);
				list.add(u);
			}
		}
		return list;
	}	
	//获取关注列表，不是粉丝列表
	public static List getUsersOfGuanzhu(WeiboAccount account){
		List list=new ArrayList();
		for(int i=0;i<=account.getGuanzhu();i=i+200){
			UserWapper users=WeiboRelation.getFriendsByUid(account.getAccess_token(),account.getUid(),200,i);
			for(int j=0;j<users.getUsers().size();j++){
				User u=users.getUsers().get(j);
				list.add(u);
			}
		}
		return list;
	}


	//获取关注列表，我关注了他，他没关注我的人
	public static List getUsersOfGuanzhu(String token,String uid,int guanzhu,int fensi){
		List list=new ArrayList();
		for(int i=0;i<=guanzhu;i=i+200){
			UserWapper users=WeiboRelation.getFriendsByUid(token,uid,200,i);
			for(int j=0;j<users.getUsers().size();j++){
				User u=users.getUsers().get(j);
				list.add(u);
			}
		}
		List list2=new ArrayList();
		for(int i=0;i<=fensi;i=i+200){
			UserWapper users=WeiboRelation.getFollowersByUid(token,uid,200,i);
			for(int j=0;j<users.getUsers().size();j++){
				User u=users.getUsers().get(j);
				list2.add(u);
			}
		}
		return Util.getDiffrent(list,list2);
	}
	public static List getUsersOfGuanzhu(WeiboAccount account,String uid,int guanzhu){
		List list=new ArrayList();
		for(int i=0;i<=guanzhu;i=i+200){
			UserWapper users=WeiboRelation.getFriendsByUid(account.getAccess_token(),uid,200,i);
			for(int j=0;j<users.getUsers().size();j++){
				User u=users.getUsers().get(j);
				list.add(u);
			}
		}
		return list;
	}
	public static Status getLastedTopic(String access_token,String name){
		Status s=null;
		StatusWapper status=WeiboMessage.getLastedByUser(access_token, name,1);
		List l=status.getStatuses();
		for(int j=0;j<l.size();j++){
			s=(Status) l.get(j);
		}
		return s;
	}
	public static Map getLastedTopicContent(WeiboAccount account,String name){
		Map c=new HashMap();
		c.put("ad", "0");
		String content="";
		StatusWapper status=WeiboMessage.getLastedByUser(account.getAccess_token(), name,1);
		List l=status.getStatuses();
		for(int j=0;j<l.size();j++){
			Status s=(Status) l.get(j);
			content=s.getText();
			Pattern p = Pattern.compile("http://t.cn/.*?(\\s)");
			Matcher m = p.matcher(content);
			if(m.find()==true){
				for(int o=0;o<=m.groupCount();o++){  
					content=content.replaceAll(m.group(o), " "); 
				}  
			}
			p = Pattern.compile("http://t.cn/.*");
			m = p.matcher(content);
			if(m.find()==true){
				for(int o=0;o<=m.groupCount();o++){  
					content=content.replaceAll(m.group(o), " "); 
				}  
			}
			content=content.replaceAll("#", "");
			String str1;
			String str2;
			p = Pattern.compile("#(.*?)#"); //这个可以自定义的
			m = p.matcher(content);
			boolean isfind=false;
			while(m.find()){ 
				str1 = m.group();
				String[] sendto=m.group().substring(0).split("#");
				System.out.println(sendto[1]);
				str2 = content.replaceAll(str1,"#"+account.getName()+"#"); //替换符号之间的内容
				content=str2;
				isfind=true;
			}
			if(!isfind&&account.getName()!=null)
				content="#"+account.getName()+"#"+content+" 微信号:ctosalon ";
			c.put("content", content);
			if(!s.getThumbnailPic().equals("")&&s.getThumbnailPic()!=null)
				c.put("pic", s.getThumbnailPic().replaceAll("thumbnail", "bmiddle"));//原微博图片链接
			else
				c.put("pic", account.getWeixinpic());//原微博图片链接
			/*
			if(!pic.equals("")){
				ShortUrl su = new ShortUrl();
				su.client.setToken(access_token);
				try {
					JSONObject jo =  su.longToShortUrl(pic);
					try {
						pic=jo.getJSONArray("urls").getString(2);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (WeiboException e) {
					e.printStackTrace();
				}
			}*/
		}
		return c;
	}
	//采集各大主流it微博账号的最新文章进行发表
	//关键字：创业、投资、技术、开发
	//并且@我关注的人（不包括互相关注）1个,@我互相关注的人1个,@it机构1个
	//长度小于280
	public static void sendLastedTopic(WeiboAccount account) {
		List users=account.getGuanzhulist();
		int g=0;
		int p=0;
		QueueUtil u=new QueueUtil(6);//6次发文不重复
		while(true){
			int random=(int)(Math.random()*account.getFilter().size());
			String name=(String) account.getFilter().get(random);//随机获取微博账户
			Map status=new HashMap();
			if(p%6==0)
				status=WeiboContants.getAD(account);//插播广告
			else
				status=getLastedTopicContent(account,name);//微博内容
			String content=(String) status.get("content");
			String pic=(String)status.get("pic");
			if(content.indexOf("//@")==-1&&weiboLength(content)>140&&weiboLength(content)<280){
				//String value=(String) account.getFilter().get(random);
				if(!u.contains(content)){
					if(((String)status.get("ad")).equals("1")){
						for(int i=0;i<users.size();i++){
							int id=(int)(Math.random()*users.size());
							if(weiboLength(content+"@"+((User)users.get(id)).getName())<280)
								content=content+"@"+((User)users.get(id)).getName();
							else
								break;
						}
					}else{
						for(int i=0;i<users.size();i++){
							int id=(int)(Math.random()*users.size());
							if(weiboLength(content+"@"+((User)users.get(id)).getName())<280){
								content=content+"@"+((User)users.get(id)).getName();
								break;
							}else
								break;
						}
					}

					//WeiboMessage.sendOfPicUrl(account.getAccess_token(), content, pic);//高级接口
					WeiboMessage.sendOfPic(account.getAccess_token(), content, pic);
					//WeiboMessage.send(account.getAccess_token(),content);
					System.out.println(content);
					u.offer(content);
					try {
						Thread.sleep(2000000);//1fenzhong3600000
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					g=0;
					p=p+1;
				}
			}
			g=g+1;
			if(g==15){//休息会,防止访问次数过多
				try {
					Thread.sleep(1800000);//1fenzhong3600000
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				g=0;
			}
		}
	}
	public static void sendAD(WeiboAccount account) {
		List users=getUsersOfGuanzhu(account);
		int g=0;
		//Map map=new HashMap();
		while(true){
			int random=(int)(Math.random()*account.getFilter().size());
			//String name=(String) account.getFilter().get(random);//随机获取微博账户
			String content=WeiboContants.ad;//微博内容
			if(content.indexOf("//@")==-1&&content.length()>70){
				String value=(String) account.getFilter().get(random);
				if(value!=null&&!value.equals(content)){
					for(int i=0;i<users.size();i++){
						int id=(int)(Math.random()*users.size());
						if(weiboLength(content+"@"+((User)users.get(id)).getName())<280)
							content=content+"@"+((User)users.get(id)).getName();
						else
							break;
					}
					WeiboMessage.send(account.getAccess_token(),content);
					System.out.println(content);
					//map.put(name,value);
					try {
						Thread.sleep(7200000);//1fenzhong3600000
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					g=0;
				}
			}
			g=g+1;
			if(g==15){//休息会,防止访问次数过多
				try {
					Thread.sleep(1800000);//1fenzhong3600000
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				g=0;
			}
		}
	}
	//评论我的关注的人的最新帖子
	//同时@他的关注列表里的人
	public static void commentFriendsLastedTopic(WeiboAccount account){
		//获取我关注的人
		List users=getUsersOfGuanzhu(account,account.getUid(),account.getGuanzhu());
		List users2=new ArrayList();
		while(true){
			//获取我关注的人下面他关注的人列表
			User who=(User)users.get((int)(Math.random()*users.size()));
			List usersusers=getUsersOfGuanzhu(account,who.getId(),who.getFriendsCount());
			for(int i=0;i<usersusers.size();i++){   
				String desc=((User)usersusers.get(i)).getDescription();
				//筛选符合条件的人
				for(int j=0;j<account.getDesc_key().size();j++){
					if(desc.indexOf((String)account.getDesc_key().get(j))!=-1){
						users2.add((User)usersusers.get(i));
						break;
					}
				}
			}
			System.out.println("符合条件的人："+users2.size());
			//筛选我已经关注的人
			for(int m=0;m<users2.size();m++){
				for(int n=0;n<users.size();n++){
					if(((User)users2.get(m)).getName().equals(((User)users.get(n)).getName())){
						users2.remove((User)users2.get(m));
						break;
					}
				}
			}
			System.out.println("最后符合条件的人："+users2.size());
			for(int i=0;i<users2.size();i++){
				User user=(User) users2.get(i);
				String name=user.getName();//随机微博账户
				Status status=getLastedTopic(account.getAccess_token(),name);//微博内容
				//String content=account.getDescription()+","+WeiboContants.contents[(int)(Math.random()*WeiboContants.contents.length)]+"//";//+"@"+s.getUser().getName()+"";
				String content=account.getDescription()+",请关注我//";
				if(status.getText().length()>4){//条件，还可以添加发表日期，7天之内
					//在线否
					for(int r=0;r<usersusers.size();r++){
						User user3=(User)usersusers.get((int)(Math.random()*usersusers.size()));
						if(user3.getonlineStatus()!=0){
							if(weiboLength(content+"@"+user3.getName())<140)
								content=content+"@"+user3.getName();
							else
								break;
						}
					}
					//随即
					for(int e=0;e<usersusers.size();e++){
						User user4=(User)usersusers.get((int)(Math.random()*usersusers.size()));
						String name_=user4.getName();
						if(weiboLength(content+"@"+name_)<140)
							content=content+"@"+name_;
						else
							break;
					}
					WeiboComment.comment(account.getAccess_token(),status.getId(),content,1);
					System.out.println(content);
					System.out.println("在线用户功能未开启好像：");
					System.out.println(name);
					try {
						Thread.sleep(180000);//3分钟
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
		}
	}
	//评论最新200条微博
	//长度小于140
	public static void commentWeiboLastedTopic(WeiboAccount account){
		while(true){
			StatusWapper status=WeiboMessage.getLastedPublic(account.getAccess_token(),50);//获取200条最新微博
			List l=status.getStatuses();

			for(int i=0;i<l.size();i++){
				Status s=(Status)l.get(i);
				//String content=account.getDescription()+","+WeiboContants.contents[(int)(Math.random()*WeiboContants.contents.length)]+"//";//+"@"+s.getUser().getName()+"";
				String content="帮你转了,一起互粉下,偶微信号:ctosalon,加我晚上聊   //"+"@"+s.getUser().getName();
				while(true){
					String name=((Status)l.get((int)(Math.random()*l.size()))).getUser().getName();
					if(weiboLength(content+"@"+name)<140)
						content=content+"@"+name;
					else
						break;
				}
				WeiboComment.comment(account.getAccess_token(),s.getId(),content,1);
				System.out.println(content);
				System.out.println(s.getUser().getName());
				try {
					Thread.sleep(180000);//3分钟
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			try {
				Thread.sleep(30000);//半分钟
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	//获取字符串的长度，如果有中文，则每个中文字符计为2位
	//微博长度为280
	public static int weiboLength(String value) {
		int valueLength = 0;
	    String chinese = "[\u0391-\uFFE5]";
	    /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
	    for (int i = 0; i < value.length(); i++) {
	    	/* 获取一个字符 */
	    	String temp = value.substring(i, i + 1);
	    	/* 判断是否为中文字符 */
	    	if (temp.matches(chinese)) {
	    		/* 中文字符长度为2 */
	    		valueLength += 2;
	    	} else {
	    		/* 其他字符长度为1 */
	    		valueLength += 1;
	    	}
	    }
	    return valueLength;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//创建一个线程池 
        ExecutorService pool = Executors.newFixedThreadPool(4);
        for(int i = 0; i<WeiboContants.accounts.size(); i++){
        	WeiboAccount account=(WeiboAccount) WeiboContants.accounts.get(i);
        	pool.submit(new DoSendLastedTopic(account));
            pool.submit(new DoCommentLastedTopic(account));
            //pool.submit(new DoSendAD(account));
            //pool.submit(new DoCommentFriendsLastedTopic(account));
            try {
    			Thread.sleep(( long ) (Math.random() * 6000 ));
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} 
        }
        pool.shutdown();
	}

}
